﻿var app = new Vue({
    el: '#DATABI_YBZZ',
    components: {

    },
    data: {
        vtype: ComFunJS.getQueryString('vtype', '0'),
        piid: ComFunJS.getQueryString('piid', '0'),
        pddata: {},
        pidata: {},
        formLabelWidth: '120px',
        poption: { width: '0' },
        FormCode: "BDGL",
        FormFile: [],
        FormDecVisible: false,
        dialogCanVisible: false,
        tdpro: { shname: "审核" },
        canlx: "0",
        canyj: "",
        formtemp: "",
        formtatus: "0",
        bodyopacity: 95,
        tabtype: "0",
        isview: false,//是否浏览模式,判断需不需要加载默认值
        nowwidget: {},
        wfdata: [],
        readySize: 0,//组件加载数据
        NoValData: [],//不需要验证字段
        FormData: {
            wigetitems: []
        },
        qxdata: { ISCANSP: "N", ISCANCEL: "N" },
        nowwidget: {
        },
        zduser: [],
        zsr: '',
        lcshow: false,
        taskorder: '0',
        tatag: true,//题按专用参数

    },
    computed: {
        //isrebackone() {
        //    return app.wfdata[1].TIData == "";
        //}
    },
    methods: {
        on_click: function (item) {
            alert(item.TaskName)
        },
        addchildwig() {
            this.readySize++
            // 检查进度是否设置的colSize一致
            if (this.readySize == this.FormData.wigetitems.length) {
                this.layout();
            }
        },
        handleCommand(command) {
            if (command == "CopyForm") {
                this.CopyForm();
            }
            if (command == "UpdateTemp") {
                this.UpdateTemp();
            }
            if (command == "Export") {
                this.Export();
            }
            if (command == "Preview") {
                Preview();
            }
            if (command == "zdh") {
                this.zdh();
            }
            if (command == "qp") {
                this.qp();
            }
        },
        jxfiled: function (nowwidget, jxdata) {
            var js = [];
            if (_.isArray(jxdata)) {
                js = jxdata || JSON.parse(nowwidget.staticdata);

            } else {
                js = JSON.parse(jxdata || nowwidget.staticdata);
            }
            nowwidget.tabfiledlist = [];
            _.forEach(_.keys(js[0]), function (value) {
                var fid = {
                    ColumnName: value,
                    ColumnType: "Str",
                    Dimension: "1",
                    Name: value,
                }
                if (_.findIndex(nowwidget.tabfiledlist, function (o) { return o.ColumnName == fid.ColumnName; }) == -1) {
                    nowwidget.tabfiledlist.push(fid);
                }
            });
        },//解析数据维度
        jxparam: function (val) {
            //解析参数
            var valsql = "";
            if (val) {
                valsql = val;
                var regex2 = /\[(.+?)\]/g;
                var temp = val.match(regex2);
                _.forEach(temp, function (obj) {
                    var tempqval = "";
                    obj = _.trim(obj, '[');
                    obj = _.trim(obj, ']');
                    if (_.startsWith(obj, '&')) {
                        tempqval = ComFunJS.getQueryString(obj.split('&')[1]);
                        valsql = _.replace(valsql, '[' + obj + ']', tempqval);
                    }
                    if (_.startsWith(obj, '@')) {
                        tempqval = ComFunJS.getCookie(obj.split('@')[1]);
                        valsql = _.replace(valsql, '[' + obj + ']', tempqval);
                    }
                    if (_.startsWith(obj, '$')) {
                        var wig = _.find(app.FormData.wigetitems, function (o) {
                            return o.wigdetcode == obj.split('$')[1];
                        })
                        tempqval = wig.value;//获取组件值
                        valsql = _.replace(valsql, '[' + obj + ']', tempqval);
                    }
                })
            }
            return valsql;
        },
        getwiget: function (wiggetcode) {
            var datawig = null;
            _.forEach(app.FormData.wigetitems, function (item) {
                if (item.wigdetcode == wiggetcode) {
                    datawig = item;
                }
            })
            return datawig;
        },
        UpdateYBData: function (nowwidget) {
            if (nowwidget.datatype == '2') {//静态数据
                try {
                    if (nowwidget.staticdata) {
                        app.jxfiled(nowwidget, nowwidget.staticdata)
                        var js = JSON.parse(nowwidget.staticdata);
                        var lastdata = js;
                        nowwidget.dataset = lastdata;
                    }

                } catch (e) {
                    app.$notify({
                        title: '失败',
                        message: '错误得JSON格式',
                        type: 'error'
                    });
                }
                return;
            }

            //需要先克隆一个对象,不然没法解析参数
            var tempnow = _.cloneDeep(nowwidget);
            if (tempnow.apiurl.indexOf("http:") == -1) {
                tempnow.apiurl = window.document.location.origin + '/' + tempnow.apiurl;
            }
            if (tempnow.datatype == '3' || tempnow.datatype == '1') {
                //处理存储过程和API得参数
                _.forEach(tempnow.proqdata, function (obj) {
                    obj.pvalue = app.jxparam(obj.pvalue);
                })

            } else {
                //处理查询参数
                _.forEach(tempnow.wdlist, function (wd) {
                    if (wd.querydata.length > 0) {
                        _.forEach(wd.querydata, function (wdq) {
                            wdq.glval = app.jxparam(wdq.glval);

                        })
                    }
                })
                //处理查询参数
            }

            $.getJSON('/api/Bll/ExeAction?Action=FORMBI_GETYBDATA', { P1: JSON.stringify(tempnow), pagecount: 0, pageNo: 0, pageSize: 0 }, function (resultData) {
                if (!resultData.ErrorMsg) {
                    nowwidget.dataset = [];
                    if (nowwidget.datatype == "0") {
                        nowwidget.datatotal = resultData.DataLength;
                        nowwidget.dataset = resultData.Result;
                    } else {
                        if (resultData.Result) {
                            try {
                                if (nowwidget.datatype == "1" && nowwidget.apiurl.indexOf("http:") == -1) {
                                    resultData.Result = JSON.parse(resultData.Result).Result;//本地服务处理API
                                }
                                app.jxfiled(nowwidget, resultData.Result)
                                var tempdata = [];
                                if (_.isArray(resultData.Result)) {
                                    tempdata = resultData.Result;

                                } else {
                                    tempdata = JSON.parse(resultData.Result);
                                }
                                var lastdata = app.datamange(tempdata, nowwidget);
                                nowwidget.dataset = lastdata;
                            } catch (e) {
                                app.$notify({
                                    title: '失败',
                                    message: '获取数据格式错误',
                                    type: 'error'
                                });
                            }
                        }

                    }
                }
            })
        },
        layout: function () {
            app.FormData.wigetitems.forEach(function (wig) {
                if (wig.component == "qjTab") {
                    wig.childpro.Tabs.forEach((tab, index) => {
                        tab.content.forEach((tabitem, indexitem) => {
                            $("#" + wig.wigdetcode).find(".el-tab-pane").eq(index).append($("#" + tabitem.wigdetcode));
                        })
                    })
                }
            })
        },
        zdh: function () {
            $(".containerb").toggleClass("widthmax");
            $(".elmain").toggleClass("pd40");
            $(".elmain").toggleClass("pd0");

        },
        CopyForm: function () {
            this.$confirm('此操作将会把此表单作为模板,重新发起表单,是否转到发起页面?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true

            }).then(() => {
                localStorage.setItem("copydata", JSON.stringify(app.FormData));
                location.href = "/ViewV5/AppPage/FORMBI/FormAdd.html?iscopy=y&pdid=" + app.pddata.ID + "&r=" + Math.random();
            }).catch(() => {

            });
        },
        UpdateTemp: function () {
            this.$confirm('检测到模板数据有更新?需要更新到新得模板吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true

            }).then(() => {
                var tempwigs = JSON.parse(app.formtemp);
                _.forEach(tempwigs, function (temp) {
                    if (_.findIndex(app.FormData.wigetitems, function (wig) {
                        return wig.wigdetcode == temp.wigdetcode;
                    }) == -1) {
                        app.FormData.wigetitems.push(temp);
                    }
                })
            }).catch(() => {

            });
        },
        changeop: function (val) {
            $("body").css("opacity", "." + val);
            localStorage.setItem("fopacity", val);
        },
        qp: function () {
            if (document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen) {
                ComFunJS.exitFullscreen()
            } else {
                ComFunJS.requestFullScreen();
            }
        },
        stepstatus: function (taskstatus) {
            switch (taskstatus) {
                case "1":
                    return "success";
                    break;
                case "-1":
                    return "danger";
                    break;
                default:
                    return ""
            }
        },
        SaveDraft: function () {
            var draftdata = { "ID": "0", "FormCode": app.FormCode, "FormID": app.pddata.ID, "JsonData": "" };
            draftdata.JsonData = JSON.stringify(app.FormData.wigetitems);
            $.getJSON("/api/Bll/ExeAction?Action=FORMBI_SAVEDRAFT", { P1: JSON.stringify(draftdata) }, function (result) {
                if (!result.ErrorMsg) {

                }
            })
        },
        SaveForm: function () {
            if (app.piid != 0) {
                $.getJSON("/api/Bll/ExeAction?Action=FORMBI_SAVEPIDATA", { P1: app.piid, P2: JSON.stringify(app.FormData.wigetitems) }, function (result) {
                    if (!result.ErrorMsg) {
                        app.$notify({
                            title: '成功',
                            message: '更新表单成功',
                            type: 'success'
                        });
                        if (app.pidata.PITYPE == "-1") {
                            try {
                                let jscode = app.poption.completecode;
                                let func = new Function('piid', jscode);
                                func(app.piid)
                            } catch (e) {

                            }
                        }
                    }
                });
            }
        },
        ManageForm: function () {
            if (app.poption.mangecode) {
                try {
                    let jscode = app.poption.mangecode;
                    let func = new Function('taskorder', jscode);
                    var mr = func(app.taskorder);
                    if (mr) {
                        return;
                    }
                } catch (e) {

                }
            }

            this.$refs.form.validate(function (boolean, object) {
                if (app.NoValData.length > 0) {
                    app.$refs.form.clearValidate(app.NoValData);
                }//遇到不需要验证得,先去除验证
                if (_.difference(_.keys(object), app.NoValData).length == 0) {
                    app.$prompt('请输入意见', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputValue: "同意"
                    }).then(({ value }) => {
                        $.getJSON("/api/Bll/ExeAction?Action=FORMBI_MANAGEWF", { P1: app.piid, P2: value, formcode: app.FormCode, csr: "", content: JSON.stringify(app.FormData.wigetitems) }, function (result) {
                            if (!result.ErrorMsg) {
                                app.$notify({
                                    title: '成功',
                                    message: '审核完毕',
                                    type: 'success'
                                });
                                app.qxdata = { ISCANSP: "N", ISCANCEL: "N" };
                                app.formtatus = "1";
                            }
                        });
                    }).catch(() => {

                    });
                }
            })


        },
        ReForm: function () {
            if (!app.zsr) {
                app.$message({
                    type: 'info',
                    message: '请选择转审人员'
                });
                return;
            }
            app.$prompt('请输入转审意见', '提示', {
                confirmButtonText: '确定转审',
                cancelButtonText: '取消',
                inputValue: ""
            }).then(({ value }) => {
                $.getJSON("/api/Bll/ExeAction?Action=FORMBI_MANAGEWF", { P1: app.piid, P2: value, zsr: app.zsr, formcode: app.FormCode, csr: "", content: JSON.stringify(app.FormData.wigetitems) }, function (result) {
                    if (!result.ErrorMsg) {
                        app.$notify({
                            title: '成功',
                            message: '转审完毕',
                            type: 'success'
                        });
                        app.qxdata = { ISCANSP: "N", ISCANCEL: "N" };
                        app.formtatus = "1";
                    }
                });
            }).catch(() => {
                app.$message({
                    type: 'info',
                    message: '已取消转审操作'
                });
            });
        },
        CanCel: function () {
            this.$confirm('此操作将撤回您发起的表单,撤回后您可以到该表单的草稿箱中找到撤回的数据,是否继续?', '提示', {
                confirmButtonText: '确定撤回',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                $.getJSON("/api/Bll/ExeAction?Action=FORMBI_CANCELWF", { P1: app.piid, ModelCode: app.FormCode }, function (result) {
                    if (!result.ErrorMsg) {//流程数据
                        app.qxdata.ISCANCEL = "N";
                        app.SaveDraft();
                        app.$message({
                            type: 'info',
                            message: '已撤回成功'
                        })
                    }
                })

            }).catch(() => {
                app.$message({
                    type: 'info',
                    message: '已取消撤回操作'
                });
            });
        },
        ReBack: function () {
            app.dialogCanVisible = true;
        },
        ConReBack: function () {
            if (!app.canyj) {
                app.$notify({
                    title: '警告',
                    message: '请输入意见',
                    type: 'warning'
                });
            } else {
                $.getJSON("/api/Bll/ExeAction?Action=FORMBI_REBACKWF", { P1: app.piid, P2: app.canyj, formcode: app.FormCode, cantype: app.canlx }, function (result) {
                    if (!result.ErrorMsg) {
                        app.$notify({
                            title: '成功',
                            message: '操作成功',
                            type: 'success'
                        });
                        location.reload()
                    }
                });
            }

        },
        RemindForm: function () {

        },
        Export: function () {
            //location.href = "/api/Bll/EXPORTWORD?P1=" + app.pddata.ID + "&P2=" + app.piid;
            $.getJSON("/api/Bll/ExeAction?Action=FILE_EXPORTWORD", { P1: app.pddata.ID, P2: app.piid }, function (result) {
                location.href = "/Export/" + result.Result;
            })
        },
        initwf: function () {
            $.getJSON("/api/Bll/ExeAction?Action=FORMBI_GETMANGWFDATA", { P1: app.piid }, function (result) {
                if (result.ErrorMsg == "") {

                    app.formtemp = result.Result1.Tempcontent;

                    var wigs = JSON.parse(result.Result3.Content);
                    app.wfdata = result.Result;
                    app.pddata = result.Result1;
                    app.qxdata = JSON.parse(result.Result2);
                    app.pidata = result.Result3;
                    app.FormFile = result.Result4;
                    app.taskorder = result.Result5;

                    if (app.pddata.Poption) {
                        app.poption = JSON.parse(app.pddata.Poption);
                    }
                    if (app.qxdata.ISCANCEL == "Y") {
                        try {
                            var tempwigs = JSON.parse(app.formtemp);
                            if (wigs.length < tempwigs.length) {
                                app.UpdateTemp();
                            }

                        } catch (e) {

                        }
                    }

                    app.FormData.wigetitems = wigs;
                    if (app.pddata.ProcessType != "-1") {
                        var writefiled = [];
                        if (app.qxdata.ISCANCEL == "Y" && app.qxdata.ISCANSP != "Y") {
                            //可以撤回并且不能审批时为第一个节点
                            writefiled = app.wfdata[0];
                        } else {
                            if (app.pidata.IsCanceled == "Y") {
                                writefiled = _.find(app.wfdata, function (item) {
                                    return item.state == "-1";
                                })
                            } else {
                                writefiled = _.find(app.wfdata, function (item) {
                                    return !item.EndTime;
                                })
                            }

                        }

                        if (writefiled) {

                            if (app.pidata.isComplete == 'Y') {
                                writefiled.WritableFields = "";
                                writefiled.ReadableFields = "";

                            }

                            var intindex = 0;
                            _.forEach(app.FormData.wigetitems, function (wiget) {
                                if (wiget.childpro.hasOwnProperty('disabled')) {
                                    if (app.pidata.IsCanceled == "Y") {
                                        wiget.childpro.disabled = true;
                                    } else {
                                        wiget.childpro.disabled = _.indexOf(writefiled.WritableFields.split(','), wiget.wigdetcode) == -1;
                                    }
                                }
                                if (wiget.childpro.hasOwnProperty('hide')) {
                                    wiget.childpro.hide = _.indexOf(writefiled.ReadableFields.split(','), wiget.wigdetcode) > -1;
                                }
                                if (wiget.childpro.disabled) {
                                    app.NoValData.push("wigetitems." + intindex + ".value")
                                }//具有权限才能编辑,否则加到不需验证数据中去
                                intindex++;
                            })

                            if (app.wfdata.length > 0) {

                                if (writefiled.isCanEdit) {
                                    app.tdpro = JSON.parse(writefiled.isCanEdit);
                                    if (app.tdpro.nocal) {
                                        app.canlx = "1";
                                    }
                                    if (writefiled.Taskorder == "2") {
                                        app.tdpro.nocalre = true;
                                    }
                                    _.forEach(writefiled.RBData, function (chi) {
                                        if (chi.IsHasManager == "转审") {
                                            app.tdpro.zhuandan = false;
                                        }
                                    })
                                    _.forEach(writefiled.RBData, function (chi) {
                                        if (chi.IsHasManager == "退回上一步") {
                                            app.tdpro.nocalre = true;
                                            app.tdpro.nocal = true;
                                            app.tatag = false;
                                        }
                                    })
                                    //可以转单
                                    if (app.tdpro.zhuandan) {
                                        $.getJSON('/api/Auth/ExeAction?Action=GETROLEBYCODE', { "P1": app.tdpro.zdrole }, function (resultData) {
                                            if (resultData.ErrorMsg == "") {
                                                app.zduser = resultData.Result1;
                                            }
                                        })
                                    }
                                }

                            }
                        }
                        if (app.pidata.isComplete == 'Y') {
                            _.forEach(app.FormData.wigetitems, function (wiget) {
                                wiget.childpro.disabled = true;

                            })
                        }
                    }



                }
            })

        },
        datamange: function (data, nowwidget) {
            const dv = new DataSet.View().source(data);
            var redata = [];

            //数据过滤
            //获取数据筛选条件
            var qdata = [];
            _.forEach(nowwidget.wdlist, function (wd) {
                if (wd.querydata.length > 0) {
                    _.forEach(wd.querydata, function (wdq) {
                        qdata.push({ colid: wd.colid, cal: wdq.cal, glval: wdq.glval });
                    })
                }
            })
            _.forEach(qdata, function (q) {
                var calval = app.jxparam(q.glval);
                if (calval) {
                    switch (q.cal) {
                        case "0":    //等于
                            {
                                dv.transform({
                                    type: 'filter',
                                    callback(row) { // 判断某一行是否保留，默认返回true
                                        return row[q.colid] == calval;
                                    }
                                });
                            }
                            break;
                        case "1":    //小于
                            {
                                dv.transform({
                                    type: 'filter',
                                    callback(row) { // 判断某一行是否保留，默认返回true
                                        return row[q.colid] < calval;
                                    }
                                });
                            }
                            break;
                        case "2":    //大于
                            {
                                dv.transform({
                                    type: 'filter',
                                    callback(row) { // 判断某一行是否保留，默认返回true
                                        return row[q.colid] > calval;
                                    }
                                });
                            }
                            break;
                        case "3":    //小于
                            {
                                dv.transform({
                                    type: 'filter',
                                    callback(row) { // 判断某一行是否保留，默认返回true
                                        return row[q.colid] != calval;
                                    }
                                });
                            }
                            break;
                        case "4":    //包含
                            {
                                dv.transform({
                                    type: 'filter',
                                    callback(row) { // 判断某一行是否保留，默认返回true
                                        return row[q.colid].indexOf(calval) > -1;
                                    }
                                });
                            }
                            break;
                        default: {

                        }
                    }
                }
            })
            var filds = _.map(nowwidget.wdlist, 'colid');
            if (filds.length > 0) {
                dv.transform({
                    type: 'pick',
                    fields: filds // 决定保留哪些字段，如果不传，则返回所有字段
                });
            }
            redata = dv.rows;
            return redata;
        },
        ref: function () {
            location.reload();
        },
    },
    created() {
        document.body.removeChild(document.getElementById('Loading'))
        var divBJ = document.getElementById('DATABI_YBZZ');
        divBJ.style.display = "block";
    },

    mounted: function () {
        var pro = this;
        pro.$nextTick(function () {
            var wigdata = ComFunJS.formcomponents;
            for (var i = 0; i < wigdata.length; i++) {
                pro.$options.components[wigdata[i].wigcode] = httpVueLoader(wigdata[i].wigurl);
            }
            if (!ComFunJS.isPC()) {
                pro.vtype = "1";
                $("#FormFoot").addClass("FormFoot");
                $(".el-dialog").width("90%");
            }
            if (pro.vtype == "2") {
                $("#FormFoot").addClass("FormFoot");
                //弹框模式,添加底部按钮样式,去除背景
            }
            pro.initwf();
            if (pro.vtype == "1" || pro.vtype == "2") {
                pro.zdh();
            }
            if (pro.vtype == "0") {
                $("body").css("background-color", "#e4e7ed");
                $("body").css("background-image", "url(/ViewV5/images/skin/skin7.jpg)");
            }

        })
    }

})